package library.http.progress;


import android.text.TextUtils;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.Response;

public class HttpProgressHelper {

    public static void addProgressDown(final OkHttpClient.Builder builder, final ProgressPublisher publisher) {//增加拦截器
        builder.networkInterceptors().add(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                //拦截
                Response originalResponse = chain.proceed(chain.request());
                ProgressResponseBody body = new ProgressResponseBody(originalResponse.body(), publisher);

                String contentLength = originalResponse.header("Content-Length");
                if (!TextUtils.isEmpty(contentLength) && TextUtils.isDigitsOnly(contentLength)) {
                    body.setContentLength(Long.parseLong(contentLength));
                }
                //包装响应体并返回
                return originalResponse.newBuilder()
                        .body(body)
                        .build();
            }
        });
    }


    public static ProgressRequestBody addProgressUp(final RequestBody requestBody, final ProgressPublisher publisher) {
        //包装请求体
        return new ProgressRequestBody(requestBody, publisher);
    }
}